#include <49func.h>
typedef struct shareRes_s {
    int num; //描述饭的数量
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void *threadFunc(void *arg){
    shareRes_t * pShareRes = (shareRes_t *)arg;
    //顾客
    pthread_mutex_lock(&pShareRes->mutex);
    //if(pShareRes->num == 0){
    while(pShareRes->num == 0){//把if换成while避免虚假唤醒
        pthread_cond_wait(&pShareRes->cond,&pShareRes->mutex);
    }
    printf("Before I got food! num = %d\n", pShareRes->num);
    --pShareRes->num;
    printf("After I got food! num = %d\n", pShareRes->num);
    pthread_mutex_unlock(&pShareRes->mutex);
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.num = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);
    pthread_cond_init(&shareRes.cond,NULL);
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,threadFunc,&shareRes);
    pthread_create(&tid2,NULL,threadFunc,&shareRes);
    //厨师
    sleep(3);
    pthread_mutex_lock(&shareRes.mutex);
    ++shareRes.num;
    //pthread_cond_signal(&shareRes.cond);
    pthread_cond_broadcast(&shareRes.cond);
    pthread_mutex_unlock(&shareRes.mutex);

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    return 0;
}

